package com.heima.article.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.article.mapper.ApArticleMapper;
import com.heima.article.service.*;
import com.heima.common.admin.WemediaConstants;
import com.heima.common.article.ArticleConstants;
import com.heima.common.exception.CustException;
import com.heima.common.message.NewsUpOrDownConstants;
import com.heima.feigns.AdminFeign;
import com.heima.feigns.WemediaFeign;
import com.heima.model.admin.pojos.AdChannel;
import com.heima.model.article.dtos.ArticleHomeDTO;
import com.heima.model.article.pojos.ApArticle;
import com.heima.model.article.pojos.ApArticleConfig;
import com.heima.model.article.pojos.ApArticleContent;
import com.heima.model.article.pojos.ApAuthor;
import com.heima.model.article.vos.HotArticleVo;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.wemedia.pojos.WmNews;
import com.sun.org.apache.xml.internal.dtm.ref.sax2dtm.SAX2RTFDTM;
import io.seata.spring.annotation.GlobalTransactional;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;


@Service
@Slf4j
public class ApArticleServiceImpl extends ServiceImpl<ApArticleMapper, ApArticle> implements ApArticleService {

    /**
     * wmNews  查询
     * ap_article ap_article_confg  ap_article_content  保存3表数据
     * wmNews 修改 9 article_id
     *
     * @param newsId 文章id
     */
    @Autowired
    GeneratePageService generatePageService;

    @Autowired
    RabbitTemplate rabbitTemplate;

    @GlobalTransactional(rollbackFor = Exception.class, timeoutMills = 300000)
    @Override
    public void publishArticle(Integer newsId) {
        //1.根据文章id查询自媒体信息
        WmNews wmNews = getWmNews(newsId);
        //2.根据WmNews信息封装Aparticle对象
        ApArticle article = parseApArticle(wmNews);
        //3.保存或修改apArticle对象
        saveOrUpdateApArticle(article);
        //4.保存配置信息 和 内容信息
        saveConfigAndContent(article, wmNews);
        //5. 页面静态化
        generatePageService.generateArticlePage(wmNews.getContent(), article);
        //6.修改WmNews的状态，将状态改为9 并设置关联的articleId
        updatWmNews(wmNews, article);

        //7. MQ通知es索引库 更新文章索引
        rabbitTemplate.convertAndSend(NewsUpOrDownConstants.NEWS_UP_FOR_ES_QUEUE);
        log.info("成功发送消息 索引库更新消息 文章id：{}",article.getId());

    }

    @Autowired
    ApArticleMapper apArticleMapper;

    @Value("${file.oss.web-site}")
    String webSite;

    @Value("${file.minio.readPath}")
    String readPath;

    @Override
    public ResponseResult load(Short loadtype, ArticleHomeDTO dto) {
        //1.校验参数
        Integer size = dto.getSize();
        if (size == null || size <= 0) {
            dto.setSize(10);
        }
        if (StringUtils.isNotBlank(dto.getTag())) {
            //推荐频道
            dto.setTag(ArticleConstants.DEFAULT_TAG);
        }
        if (dto.getMinBehotTime() == null) {
            dto.setMinBehotTime(new Date());
        }
        if (dto.getMaxBehotTime() == null) {
            dto.setMaxBehotTime(new Date());
        }
        if (!ArticleConstants.LOADTYPE_LOAD_MORE.equals(loadtype) && !ArticleConstants.LOADTYPE_LOAD_NEW.equals(loadtype)) {
            loadtype = ArticleConstants.LOADTYPE_LOAD_MORE;
        }
        //2.调用mapper查询文章
        List<ApArticle> articleList = apArticleMapper.loadArticleList(dto, loadtype);
        for (ApArticle article : articleList) {
            String images = article.getImages();
            if (StringUtils.isNotBlank(images)) {
                images = Arrays.stream(images.split(","))
                        .map(url -> webSite + url)
                        .collect(Collectors.joining(","));
                article.setImages(images);
            }
            //凭借静态页 访问前缀
            article.setStaticUrl(readPath+article.getStaticUrl());
        }
        //3.封装返回结果
        return ResponseResult.okResult(articleList);
    }

    @Autowired
    StringRedisTemplate redisTemplate;
    @Override
    public ResponseResult loadFromCache(Short loadtype, ArticleHomeDTO dto) {
        //1.从redis中查询指定频道的缓存数据
        String hotArticleJson = redisTemplate.opsForValue().get(ArticleConstants.HOT_ARTICLE_FIRST_PAGE + dto.getTag());
        //2.判断如果缓存为空，从数据库中查询
        if (StringUtils.isBlank(hotArticleJson)) {
            return load(loadtype,dto);
        }
        List<HotArticleVo> hotArticleVoList = JSON.parseArray(hotArticleJson, HotArticleVo.class);
        //3.如果有缓存返回缓存的热点文章列表数据
        for (HotArticleVo articleVo : hotArticleVoList) {
            //    添加图片的访问前缀   webSite + url1,url2,url3
            String images = articleVo.getImages();
            if (StringUtils.isNotBlank(images)) {
                Arrays.stream(images.split(","))
                        .map(url->webSite+url)
                        .collect(Collectors.joining(","));
                articleVo.setImages(images);
            }
            //    添加静态页的访问前缀
            articleVo.setStaticUrl(readPath+articleVo.getStaticUrl());
        }
        return ResponseResult.okResult(hotArticleVoList);
    }


    @Autowired
    WemediaFeign wemediaFeign;

    //1.根据文章id查询自媒体信息
    private WmNews getWmNews(Integer newsId) {
        //1. 根据id使用feign接口远程查询
        ResponseResult<WmNews> result = wemediaFeign.findWmNewsById(newsId);
        if (!result.checkCode()) {
            CustException.cust(AppHttpCodeEnum.REMOTE_SERVER_ERROR);
        }
        WmNews wmNews = result.getData();
        //2.判断文章是否为null
        if (wmNews == null) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST, "文章不存在");
        }
        //3.判断文章的状态必须是 4 或 8
        Short status = wmNews.getStatus();
        if (!WemediaConstants.WM_NEWS_AUTH_PASS.equals(status) && !WemediaConstants.WM_NEWS_AUTHED_STATUS.equals(status)) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_ALLOW, "文章的状态不是审核通过状态，发布文章失败");
        }
        return wmNews;
    }

    //2.根据WmNews信息封装Aparticle对象

    /**
     * @param wmNews
     * @return
     */
    @Autowired
    AdminFeign adminFeign;

    @Autowired
    AuthorService authorService;

    private ApArticle parseApArticle(WmNews wmNews) {
        //1.创建article,将WmNews的同名属性拷贝进去
        ApArticle article = new ApArticle();
        BeanUtils.copyProperties(wmNews, article);
        //2.单独设置articleId字段
        article.setId(wmNews.getArticleId());
        //3.其他需要补充字段 flag layout
        article.setLayout(wmNews.getType());
        article.setFlag((byte) 0);
        //4.频道信息
        ResponseResult<AdChannel> channelResult = adminFeign.findOne(wmNews.getChannelId());
        if (!channelResult.checkCode()) {
            CustException.cust(AppHttpCodeEnum.REMOTE_SERVER_ERROR, "远程查询频道信息失败");
        }
        AdChannel channel = channelResult.getData();
        article.setChannelName(channel.getName());
        //5.作者信息
        ApAuthor apAuthor = authorService.getOne(Wrappers.<ApAuthor>lambdaQuery().eq(ApAuthor::getWmUserId, wmNews.getUserId()));
        article.setAuthorId(Long.valueOf(apAuthor.getId()));
        article.setAuthorName(apAuthor.getName());
        return article;
    }


    @Autowired
    ApArticleConfigService apArticleConfigService;

    @Autowired
    ApArticleContentService apArticleContentService;

    //3.保存或修改apArticle对象
    private void saveOrUpdateApArticle(ApArticle article) {
        if (article.getId() == null) {
            //保存
            article.setViews(0);
            article.setLikes(0);
            article.setComment(0);
            article.setCollection(0);
            this.save(article);
        } else {
            //删除关联的 文章配置信息 和文章详情信息
            apArticleConfigService.remove(
                    Wrappers.<ApArticleConfig>lambdaQuery()
                            .eq(ApArticleConfig::getArticleId, article.getId()));

            apArticleContentService.remove(
                    Wrappers.<ApArticleContent>lambdaQuery()
                            .eq(ApArticleContent::getArticleId, article.getId()));
            //修改
            this.updateById(article);
        }
    }

    //4.保存配置信息 和 内容信息
    private void saveConfigAndContent(ApArticle article, WmNews wmNews) {
        //1.保存文章配置信息
        ApArticleConfig config = new ApArticleConfig();
        config.setArticleId(article.getId());
        config.setIsComment(true); //是否允许评论
        config.setIsForward(true);//是否允许转发
        config.setIsDown(false);//是否允许下架
        config.setIsDelete(false);//是否允许删除
        apArticleConfigService.save(config);
        //2.保存文章内容信息
        ApArticleContent content = new ApArticleContent();
        content.setArticleId(article.getId());
        content.setContent(wmNews.getContent());
        apArticleContentService.save(content);
    }

    //6.修改WmNews的状态，将状态改为9 并设置关联的articleId
    private void updatWmNews(WmNews wmNews, ApArticle article) {
        wmNews.setStatus(WmNews.Status.PUBLISHED.getCode());
        wmNews.setArticleId(article.getId());
        ResponseResult responseResult = wemediaFeign.updateWmNews(wmNews);
        if (!responseResult.checkCode()) {
            CustException.cust(AppHttpCodeEnum.REMOTE_SERVER_ERROR, "远程修改自媒体文章状态失败");
        }
    }

}